import { useActiveObject } from '@renderer/stores/activeObject'
import { ActionMode, useActionMode } from '@renderer/stores/actionMode'
import { useViewportStore } from '@renderer/stores/viewport'
import { storeToRefs } from 'pinia'
import { watch } from 'vue'
import { Object3D } from 'three'
import useEditor from '@renderer/utils/useEditor'

export default function () {
  const activeObjectStore = useActiveObject()
  const { activeVO } = storeToRefs(activeObjectStore)

  const viewportStore = useViewportStore()
  const { notPublicGroup, transformControls } = storeToRefs(viewportStore)

  const actionModeStore = useActionMode()
  const { currentMode } = storeToRefs(actionModeStore)

  function handleAction(mode: ActionMode, obj: Object3D) {
    if (['translate', 'scale', 'rotate'].includes(mode) && transformControls.value) {
      transformControls.value.mode = mode
      if (transformControls.value && notPublicGroup.value && obj) {
        transformControls.value.attach(obj)
        const transformControlsHelper = transformControls.value.getHelper()
        notPublicGroup.value.add(transformControlsHelper)
      }
    } else {
      transformControls.value.detach()
    }
  }

  watch(
    () => activeVO.value,
    (obj) => {
      if (notPublicGroup.value && transformControls.value && obj) {
        if (obj.name.includes('editor-point') && ['scale', 'rotate'].includes(currentMode.value)) {
          actionModeStore.setCurrentMode('translate')
        } else if (['createdRoadway', 'mergedRoadway'].includes(currentMode.value)) {
          actionModeStore.setCurrentMode('translate')
        }
        handleAction(currentMode.value, obj)
      } else {
        if (notPublicGroup.value && transformControls.value) {
          transformControls.value.detach()
        }
      }
    }
  )

  watch(
    () => currentMode.value,
    (mode) => {
      if (activeVO.value) {
        handleAction(mode, activeVO.value)
      }
    },
    {
      immediate: true
    }
  )
}
